const app = getApp()

const request = (url, options, isForm) => {
	return new Promise((resolve, reject) => {
		console.log( `${app.globalData.url}${url}`)
		wx.request({
			url: `${app.globalData.url}${url}`,
			method: options.method,
			
			data: options.method === 'GET'||isForm===true ? options.data : JSON.stringify(options.data),
			header: {
				'Content-Type': isForm === true ? 'application/x-www-form-urlencoded' : 'application/json; charset=UTF-8',
				'Cookie': app.globalData.header.Cookie // 看自己是否需要
			},
			success(request) {
			
			if(request.data=="no"||request.data=="noauthc"){
				wx.reLaunch({
					url: '/pages/login/login',
				})
				return 0;
			}	//无认证跳到首页
       
				if (request.header["Set-Cookie"] != null) {
					//设置cookie
					getApp().globalData.header["Cookie"] += request.header["Set-Cookie"]
				}
        
				if (request.data.code===undefined || request.data.code === 0) {
					resolve(request.data)
				} else {
					reject(request.data)
				}
			},
			fail(error) {
				reject(error.msg)
			}
		})
	})
}

const get = (url, options = {}) => {
	
	return request(url, {
		method: 'GET',
		data: options
	})
}

const post = (url, options, isForm) => {
	return request(url, {
		method: 'POST',
		data: options
	},isForm)
}

const put = (url, options) => {
	return request(url, {
		method: 'PUT',
		data: options
	})
}

// 不能声明DELETE（关键字）
const remove = (url, options) => {
	return request(url, {
		method: 'DELETE',
		data: options
	})
}

module.exports = {
	get,
	post,
	put,
	remove
}
